package com.leancloud.circle.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.aries.ui.view.title.TitleBarView;
import com.leancloud.circle.R;
import com.leancloud.circle.adapter.PhotoAdapter;
import com.leancloud.circle.manage.CirclePathManage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import tech.com.commoncore.Config;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.utils.ToastUtil;
import tech.com.commoncore.view.SpaceItemDecoration;
import tech.com.commoncore.widget.photoPicker.MyPhotoPickerActivity;

@Route(path = CirclePathManage.CIRCLE_PUBLISH_ARTICLE)
public class PublishCircleActivity extends BaseTitleActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener {
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 2;

    private EditText contentEt;

    private ArrayList<String> localImgList;
    private ArrayList<String> imageUrl;

    private RecyclerView photoRecycler;
    private PhotoAdapter photoAdapter;

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText(getResources().getString(R.string.circle_post_c))
                .setRightText(getResources().getString(R.string.circle_post_right))
                .setOnRightTextClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handlerPublishCircle();
                    }
                });
    }

    private void handlerPublishCircle() {
//        if (photoAdapter.getData() == null || photoAdapter.getData().isEmpty()) {
//            publish("");
//        } else {
//            imageUrl = new ArrayList<>();
//            showLoading();
//            String token = UserGlobal.getCurrentUser().getToken();
//            for (String url : photoAdapter.getData()) {
//                uploadImageFile(token, url);
//            }
//        }
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_publish_cirlce;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        contentEt = findViewById(R.id.circle_content_et);
        findViewById(R.id.add_photo_img).setOnClickListener(this);

        photoRecycler = findViewById(R.id.circle_select_images);
        photoAdapter = new PhotoAdapter(R.layout.circle_item_photo_);
        photoRecycler.addItemDecoration(new SpaceItemDecoration((int) mContext.getResources().getDimension(R.dimen.dp_3)));
        photoRecycler.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        photoRecycler.setAdapter(photoAdapter);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.add_photo_img) {
            choicePhotoWrapper();
        }
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Config.PHOTO_PATH);
            Intent photoPickerIntent = new MyPhotoPickerActivity.IntentBuilder(this)
                    .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                    .selectedPhotos(mPhotoLayout.getData()) // 当前已选中的图片路径集合
                    .maxChooseCount(3) // 图片选择张数的最大值
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.tip_photo_permissions_request), PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            ToastUtil.show(R.string.tip_photo_permissions_denied);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            localImgList = MyPhotoPickerActivity.getSelectedPhotos(data);
            photoAdapter.replaceData(localImgList);
        }
    }

    private synchronized void uploadImageFile(String token, String fileUrl) {
//        UserGlobal.getUserImp().uploadImage(token, fileUrl, new LoginBack<ImageInfo>() {
//            @Override
//            public void onBack(ImageInfo info, String err) {
//                if (err == null) {
//                    imageUrl.add(info.getComplete_url());
//                    if (imageUrl.size() == localImgList.size()) {
//                        publish(getImages(imageUrl));
//                    }
//                } else {
//                    hideLoading();
//                    imageUrl.clear();
//                    ToastUtil.show("图片上传失败,请重新发布");
//                }
//            }
//        });
    }

    private void publish(String images) {
        String content = contentEt.getText().toString();
        if (content.isEmpty()) {
            ToastUtil.show(getResources().getString(R.string.circle_content_hint));
            return;
        }
        showLoading(getResources().getString(R.string.circle_postting));
//        CurrentUser user = UserGlobal.getCurrentUser();
//        CircleGlobal.getCircleImp().publishCircle(user.getToken(), user.getNickName(), content, images, CircleGlobal.CurrentType, -1, new CircleBack() {
//            @Override
//            public void onBack(Object o, String err) {
//                hideLoading();
//                if (err == null) {
//                    ToastUtil.show("表发成功");
//                    BusManager.getBus().post(new CircleEvent());
//                    finish();
//                } else {
//                    ToastUtil.show("发表失败," + err);
//                }
//            }
//        });
    }

    private String getImages(ArrayList<String> strings) {
        String images = "";
        for (String s : strings) {
            if (images.isEmpty()) {
                images = s;
            } else {
                images = images + "," + s;
            }
        }
        return images;
    }
}
